package com.dingwen.treasure.mybatisplus.init;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingwen.treasure.base.constant.RedisConstant;
import com.dingwen.treasure.base.enums.StatusEnum;
import com.dingwen.treasure.common.redis.service.RedisService;
import com.dingwen.treasure.model.entity.mybatisplus.SysConfig;
import com.dingwen.treasure.mybatisplus.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 　SysConfigInit
 * 　@author dingwen
 * 　@date 2022/6/2
 */
@Component
@Slf4j
public class SysConfigInit implements ApplicationRunner {

    /**
     * redis 服务
     */
    @Resource
    private RedisService redisService;

    /**
     * 系统配置
     */
    @Resource
    private SysConfigService sysConfigService;


    /**
     * 将系统配置加载到redis
     */
    private void loadSysConfigToRedis() {
        // 查询所有可用的系统配置信息
        LambdaQueryWrapper<SysConfig> lambdaQueryWrap = new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getStatus, StatusEnum.NORMAL);
        List<SysConfig> sysConfigs = sysConfigService.list(lambdaQueryWrap);

        // 过滤为空的以及拼接系统配置key
        Map<String, String> sysConfigMap = sysConfigs.parallelStream()
                .filter(sysConfig -> ObjectUtil.isNotNull(sysConfig) && StrUtil.isNotBlank(sysConfig.getCode()))
                // Locale.ROOT 获取当前locale信息
                .collect(Collectors.toMap(sysConfig -> RedisConstant.SYS_CONFIG_PREFIX.concat(sysConfig.getCode().toUpperCase(Locale.ROOT)),
                        SysConfig::getValue,
                        // 当存在key冲突时取后者
                        (oldValue, newValue) -> newValue));
        // 将配置 map 存储到redis
        redisService.setCacheMap(sysConfigMap);

        // 提交修改到通道，触发刷新到JVM内存（此处必须是JSON字符串）(分布式刷新)
        redisService.convertAndSend(RedisConstant.REDIS_REFRESH_CACHE_CHANNEL_CONFIG, sysConfigMap);

        log.info("系统配置已成功加载: {}", sysConfigMap.size());

    }

    @Override
    public void run(ApplicationArguments args) {
        loadSysConfigToRedis();
    }
}
